<?php

// +----------------------------------------------------------------------
// | MyCentOS
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.mycentos.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 琥珀 <317559272@qqq.com><http://www.mycentos.com>
// +----------------------------------------------------------------------
// | @date  : 2015-03-05 14:13:54
// +----------------------------------------------------------------------
// | @Last Modified by:  琥珀
// +----------------------------------------------------------------------
// | @Last Modified time: 2015-03-18 16:28:33
// +-----------------------------------------------------------------------


/**
 * 控制器初始化
 * @authors 琥珀 (317559272@qq.com)
 */
namespace Admin\Controller;
use Think\Controller;
use Think;
use Think\Model\RelationModel;
use Admin\Model\AuthRuleModel;
Class AdminController extends Controller
{
    protected function _initialize() {
        define('ID', is_login());
        if (!ID) {
            $this->redirect('Public/login');
        }

        // 是否是超级管理员
        define('IS_ROOT', is_administrator());

        // 检测系统权限
        if (!IS_ROOT) {
            $access = $this->accessControl();
            if (false === $access) {
                $this->error('403:禁止访问');
            } elseif (null === $access) {

                //检测访问权限
                $rule = strtolower(MODULE_NAME . '/' . CONTROLLER_NAME . '/' . ACTION_NAME);
                if (!$this->checkRule($rule, array('in', '1,2'))) {
                    $this->error('未授权访问!');
                } else {

                    // 检测分类及内容有关的各项动态权限
                    $dynamic = $this->checkDynamic();
                    if (false === $dynamic) {
                        $this->error('未授权访问!');
                    }
                }
            }
        }

        //目录
        $data = $this->getMenus();
        $this->assign('menu', $data);

        //测试的
        $data = $this->getOnline();
        $this->assign('onlineuser', $data);
    }

    /**
     * Dwz系统用到参数  ajax赋值扩展
     * @access protected
     * @param array $result  引用传值
     * @return void
     */
    protected function ajaxAssign(&$result) {
        $result['statusCode'] = $result['status'];
        $result['closeCurrent'] = $_REQUEST['closeCurrent'];
        $result['message'] = $result['info'];
        $result['tabid'] = $_REQUEST['tabid'];
        $result['dialogid'] = $_REQUEST['dialogid'];
        $result['refresh'] = $_REQUEST['refresh'];
        $result['forward'] = $_REQUEST['forward'];
        $result['forwardConfirm'] = $_REQUEST['forwardConfirm'];
    }

    /**
     * Dwz系统用到参数  ajax赋值扩展 ,继承Controller的ajaxReturn
     * @access protected
     * @param array $data,$type  引用传值
     * @return void
     */
    protected function ajaxReturn($data, $type = '', $json_option = 0) {
        if (method_exists($this, "ajaxAssign")) $this->ajaxAssign($data);
        parent::ajaxReturn($data, $type);

        //调用Thinkphp的ajaxReturn

    }

    /*
    控制显示button
    */
    protected function showButton() {
        if (!IS_ROOT) {
            $add = strtolower(MODULE_NAME . '/' . CONTROLLER_NAME . '/' . 'add');
            $edit = strtolower(MODULE_NAME . '/' . CONTROLLER_NAME . '/' . 'edit');
            $del = strtolower(MODULE_NAME . '/' . CONTROLLER_NAME . '/' . 'del');
            if ($this->checkRule($add, array('in', '1,2'))) {
                $this->assign('addButton', 1);
            }
            if ($this->checkRule($edit, array('in', '1,2'))) {
                $this->assign('editButton', 1);
            }
            if ($this->checkRule($del, array('in', '1,2'))) {
                $this->assign('delButton', 1);
            }
        } else {
            $this->assign('addButton', 1);
            $this->assign('editButton', 1);
            $this->assign('delButton', 1);
        }
    }

    /**
     * 权限检测
     * @param string  $rule    检测的规则
     * @param string  $mode    check模式
     * @return boolean
     */
    final protected function checkRule($rule, $type = 1, $mode = 'url') {
        static $Auth = null;
        if (!$Auth) {
            $Auth = new \Think\Auth();
        }
        if (!$Auth->check($rule, ID, $type, $mode)) {
            return false;
        }
        return true;
    }

    /**
     * 检测是否是需要动态判断的权限
     * @return boolean|null
     *      返回true则表示当前返回false则表示当前访问无权限访问有权限
     *
     *      返回null，则表示权限不明
     *
     */
    protected function checkDynamic() {
    }

    /**
     * action访问控制,在 **登陆成功** 后执行的第一项权限检测任务
     *
     * @return boolean|null  返回值必须使用 `===` 进行判断
     *
     *   返回 **false**, 不允许任何人访问(超管除外)
     *   返回 **true**, 允许任何管理员访问,无需执行节点权限检测
     *   返回 **null**, 需要继续执行节点权限检测决定是否允许访问
     */
    final protected function accessControl() {
        $allow = C('ALLOW_VISIT');
        $deny = C('DENY_VISIT');
        $check = strtolower(CONTROLLER_NAME . '/' . ACTION_NAME);
        if (!empty($deny) && in_array_case($check, $deny)) {
            return false;

            //非超管禁止访问deny中的方法

        }
        if (!empty($allow) && in_array_case($check, $allow)) {
            return true;
        }
        return null;

        //需要检测节点权限

    }
    protected function getMenus() {
        $where['status'] = 1;
        $where['target'] = 'navtab';
        $list = M('Menu')->where($where)->order('sort asc')->field('id,pid,name,url,rel,target')->select();
        foreach ($list as $key => $value) {
            if (!IS_ROOT && !$this->checkRule(strtolower(MODULE_NAME . '/' . $value['url']), AuthRuleModel::RULE_URL, null)) {
                unset($list[$key]);
                continue;
            }
            if ($value['url']) {
                $list[$key]['url'] = '/' . $value['url'];
            }
            if ($value['pid'] ==0) {
                $list[$key]['url'] = '';
            }


        }
        return $list;
    }
    public function getOnline() {
        $user = M('Admin')->where('online = 1')->select();
        $onlineuser = array();
        foreach ($user as $key => $value) {
            if ($value['session_id']) {
                $map = array('session_id' => $value['session_id'], 'session_expire' => array('gt', NOW_TIME), 'session_data' => array('neq', ''));
                $res = D('Session')->where($map)->find();
                if ($res) {
                    $onlineuser[]['name'] = $value['realname'];
                }
            }
        }
        $onlineuser = json_encode($onlineuser, JSON_UNESCAPED_UNICODE);
        return $onlineuser;
    }

    /**
     * 通用分页列表数据集获取方法
     * @return array|false
     * 返回数据集
     */
    protected function lists($model, $where = array(), $order = '', $field = true) {
        $options = array();
        $REQUEST = (array)I('request.');
        if (is_string($model)) {
            $model = M($model);
        }
        $OPT = new \ReflectionProperty($model, 'options');
        $OPT->setAccessible(true);
        $pk = $model->getPk();
        if ($order === null) {

            //order置空

        } else if (isset($REQUEST['orderDirection']) && isset($REQUEST['orderField']) && in_array(strtolower($REQUEST['orderDirection']), array('desc', 'asc'))) {
            $options['order'] = '`' . $REQUEST['orderField'] . '` ' . $REQUEST['orderDirection'];
        } elseif ($order === '' && empty($options['order']) && !empty($pk)) {
            $options['order'] = $pk . ' desc';
        } elseif ($order) {
            $options['order'] = $order;
        }
        unset($REQUEST['orderDirection'], $REQUEST['orderField']);
        if (empty($where)) {

            // $where  =   array('status'=>array('egt',0));

        }
        if (!empty($where)) {
            $options['where'] = $where;
        }
        $options = array_merge((array)$OPT->getValue($model), $options);
        $total = $model->where($options['where'])->count();
        if (isset($REQUEST['pageSize'])) {
            $listRows = (int)$REQUEST['pageSize'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $firstRow = empty($REQUEST['pageCurrent']) ? '0' : $listRows * ($REQUEST['pageCurrent'] - 1);
        $options['limit'] = $firstRow . ',' . $listRows;

        //分页数读取配置文件或者页面传值
        $pageSize = empty($REQUEST['pageSize']) ? C('LIST_ROWS') : $REQUEST['pageSize'];
        $pageCurrent = empty($REQUEST['pageCurrent']) ? '1' : $REQUEST['pageCurrent'];

        //显示分页数
        $this->assign('total', $total);
        $this->assign('pageSize', $pageSize);
        $this->assign('pageCurrent', $pageCurrent);
        $this->assign('pagenumshown', C('PAGE_NUM_SHOWN'));
        $model->setProperty('options', $options);
        if ($model instanceof RelationModel) {
            return $model->relation(true)->field($field)->select();
        } else {
            return $model->field($field)->select();
        }
    }
    //Ajax联动根据医院获取科室
    public function get_department() {
        $Department = M('Department');
        $map['hospital_id'] = $_REQUEST['hospital_id'];
        $map['status'] = 1;
        $data = $Department->where($map)->field('id,name')->select();
        $ls = array();
        foreach ($data as $key => $value) {
            foreach ($value as $k => $v) {
                $ls[$key][] = $v;
            }
        }
        $json = json_encode($ls, JSON_UNESCAPED_UNICODE);
        echo $json;
    }
}
?>